package com.toolbox.utils;

import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.converter.PicturesManager;
import org.apache.poi.hwpf.converter.WordToHtmlConverter;
import org.apache.poi.hwpf.usermodel.Picture;
import org.apache.poi.hwpf.usermodel.PictureType;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.tool.xml.XMLWorkerHelper;

import javax.imageio.ImageIO;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.awt.image.BufferedImage;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Base64;
import java.util.List;
import java.util.UUID;

public class DocumentConverter {

    /**
     * 将HTML转换为文本
     */
    public static String htmlToText(String htmlContent) {
        Document doc = Jsoup.parse(htmlContent);
        return doc.text();
    }

    /**
     * 将Word文档转换为HTML
     */
    public static byte[] docxToHtml(byte[] docxBytes) throws Exception {
        try (ByteArrayInputStream bis = new ByteArrayInputStream(docxBytes);
             XWPFDocument document = new XWPFDocument(bis);
             ByteArrayOutputStream out = new ByteArrayOutputStream()) {

            // 这里简化实现，实际项目中应该使用Apache POI的XWPF转换器
            // 由于简化，直接返回HTML的基本结构
            String htmlContent = "<html><head><title>Converted Document</title></head><body><p>Document converted from DOCX (simplified version)</p></body></html>";
            out.write(htmlContent.getBytes());
            return out.toByteArray();
        }
    }

    /**
     * 将Word 97-2003文档转换为HTML
     */
    public static byte[] docToHtml(byte[] docBytes) throws Exception {
        try (ByteArrayInputStream bis = new ByteArrayInputStream(docBytes);
             HWPFDocument document = new HWPFDocument(bis)) {

            org.w3c.dom.Document htmlDocument = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
            WordToHtmlConverter converter = new WordToHtmlConverter(htmlDocument);

            // 设置图片管理器
            converter.setPicturesManager(new PicturesManager() {
                @Override
                public String savePicture(byte[] content, PictureType pictureType, String suggestedName, float widthInches, float heightInches) {
                    // 简化处理，实际项目中应该保存图片
                    return "data:image/" + pictureType.getExtension() + ";base64," + Base64.getEncoder().encodeToString(content);
                }
            });

            // 处理文档中的图片
            List<Picture> pictures = document.getPicturesTable().getAllPictures();
            for (Picture picture : pictures) {
                try {
                    picture.writeImageContent(new ByteArrayOutputStream());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            converter.processDocument(document);

            // 输出HTML
            try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
                Transformer transformer = TransformerFactory.newInstance().newTransformer();
                transformer.setOutputProperty(OutputKeys.INDENT, "yes");
                transformer.setOutputProperty(OutputKeys.METHOD, "html");
                transformer.transform(new DOMSource(htmlDocument), new StreamResult(out));
                return out.toByteArray();
            }
        }
    }

    /**
     * 创建临时目录
     */
    public static File createTempDirectory() throws IOException {
        String tempDir = System.getProperty("java.io.tmpdir");
        String dirName = "toolbox_" + UUID.randomUUID().toString();
        File tempFolder = new File(tempDir, dirName);
        if (!tempFolder.exists() && !tempFolder.mkdirs()) {
            throw new IOException("无法创建临时目录");
        }
        return tempFolder;
    }

    /**
     * 清理临时目录
     */
    public static void cleanupTempDirectory(File tempDir) {
        if (tempDir != null && tempDir.exists()) {
            File[] files = tempDir.listFiles();
            if (files != null) {
                for (File file : files) {
                    if (file.isDirectory()) {
                        cleanupTempDirectory(file);
                    } else {
                        file.delete();
                    }
                }
            }
            tempDir.delete();
        }
    }

    /**
     * 将DOCX文档转换为PDF
     * 注意：当前暂不支持此功能
     */
    public static byte[] docxToPdf(byte[] docxBytes) throws Exception {
        throw new UnsupportedOperationException("DOCX to PDF conversion is not supported in the current environment");
    }

    /**
     * 将HTML转换为PDF
     */
    public static byte[] htmlToPdf(byte[] htmlBytes) throws Exception {
        String htmlContent = new String(htmlBytes);
        try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
            com.itextpdf.text.Document document = new com.itextpdf.text.Document();
            PdfWriter writer = PdfWriter.getInstance(document, out);
            document.open();
            
            // 使用XMLWorkerHelper解析HTML
            XMLWorkerHelper.getInstance().parseXHtml(writer, document, 
                    new ByteArrayInputStream(htmlContent.getBytes()));
            
            document.close();
            return out.toByteArray();
        }
    }

    /**
     * 将文本转换为PDF
     */
    public static byte[] textToPdf(byte[] textBytes) throws Exception {
        String textContent = new String(textBytes);
        try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
            com.itextpdf.text.Document document = new com.itextpdf.text.Document();
            PdfWriter writer = PdfWriter.getInstance(document, out);
            document.open();
            
            // 添加文本内容
            com.itextpdf.text.Paragraph paragraph = new com.itextpdf.text.Paragraph(textContent);
            document.add(paragraph);
            
            document.close();
            return out.toByteArray();
        }
    }

    /**
     * 将PDF转换为文本
     * 注意：当前暂不支持此功能
     */
    public static byte[] pdfToText(byte[] pdfBytes) throws Exception {
        throw new UnsupportedOperationException("PDF to Text conversion is not supported in the current environment");
    }

    /**
     * 将PDF转换为图片
     * 注意：当前暂不支持此功能
     */
    public static byte[] pdfToImages(byte[] pdfBytes) throws Exception {
        throw new UnsupportedOperationException("PDF to Images conversion is not supported in the current environment");
    }

    /**
     * 将PDF转换为DOCX
     * 注意：当前暂不支持此功能
     */
    public static byte[] pdfToDocx(byte[] pdfBytes) throws Exception {
        throw new UnsupportedOperationException("PDF to DOCX conversion is not supported in the current environment");
    }
}